<?php

namespace app\api\controller;

use app\common\controller\Api;


class Wx extends Api
{
    protected $noNeedLogin = ['wxlogin','logintest','test','getPhoneLogin','wxopenid'];
    protected $noNeedRight = ['*'];


    /**
     * 小程序登录注册
     */
    public function wxlogin()
    {
        halt('暂未使用');
        $post = $this->request->post();
        empty($post['code']) && $this->error('参数有误');
        $session = $this->getSession($post['code']);

        $openid = $session['openid'];
        $have = db('user')->where('openid',$openid)->find();
        if(!empty($have)){
            $ret = $this->auth->login($openid);
        }else{
            $userInfo['openid'] = $openid;
            $str = substr($openid, -6);
            $nickname = "用户_$str";
            $ret = $this->auth->register($nickname, $str, '', '', $userInfo);
        }
        
        $ret && $this->success(__('Logged in successful'), $this->auth->getUserinfo());
        $this->error($this->auth->getError());
    }

    public function logintest()
    {
        $ret = $this->auth->login('oWe0G7Wd_gP145eEEMceH5yazOu0');

        $this->success(__('Logged in successful'), $this->auth->getUserinfo());
    }


    /**
     * 新版本获取头像昵称并修改
     * 
     */
    public function editAvatar()
    {
        $params = I('post.');

        $update = [];
        if(!empty($params['avatar'])){
            $update['avatar'] = $params['avatar'];
        }
        if(!empty($params['nickname'])){
            $update['nickname'] = $params['nickname'];
        }
        empty($update) && $this->error('请选择更改头像或昵称');

        $ret = db('user')->where('id',$this->auth->id)->update($update);
        $ret && $this->success('修改成功');
        $this->error('修改失败');
    }


    /**
     * 解析微信手机号
     * 
     */
    public function phoneDecode()
    {
        halt('暂未使用');
        $params = request()->post();
        if(empty($params['code'])){
            $this->error('参数有误');
        }
        $session = $this->getSession($params['code']);
        $session_key = $session['session_key'];

        $pc = new \app\api\service\WxphoneDecode(config('site.app_id'), $session_key);
        $errCode = $pc->decryptData($params['encryptedData'], $params['iv'], $ret);

        if ($errCode == 0) {
            // $data   "{"phoneNumber":"17688530226","purePhoneNumber":"17688530226","countryCode":"86","watermark":{"timestamp":1565839360,"appid":"wx6103c6eed5f8c89b"}}"
            $retArr = json_decode($ret);   
            $phone = $retArr->phoneNumber;
            
            $res = db('user')->where('id',$this->auth->id)->update(['mobile'=>$phone]);
            
            $res && $this->success('获取手机号成功',compact('phone'));
            $this->error('获取手机号失败');  
        }
        $this->error('解密手机号失败',$errCode);  
    }


    /**
     * 获取手机号并登录
     * 
     */
    public function getPhoneLogin()
    {
        $params = request()->post();
        if(empty($params['code'])){
            $this->error('参数有误');
        }
        $session = $this->getSession($params['code']);
        $session_key = $session['session_key'];
        $openid = $session['openid'];

        $pc = new \app\api\service\WxphoneDecode(config('site.app_id'), $session_key);
        $errCode = $pc->decryptData($params['encryptedData'], $params['iv'], $ret);

        if ($errCode != 0) {
            $this->error('解密手机号失败',$errCode); 
        }
        $retArr = json_decode($ret);   
        $phone = $retArr->phoneNumber;

        $user = \app\common\model\User::getByMobile($phone);
        if ($user) {
            if ($user->status != 'normal') {
                $this->error(__('Account is locked'));
            }
            //如果已经有账号则直接登录
            if(!$user->openid){
                $user->save(['openid'=>$openid]);
            }
            $ret = $this->auth->direct($user->id);
        } else {
            $extend = ['openid'=>$openid];
            $extend['pid'] = @$params['parent_id'] ?: 0;

            $str = substr($openid, -6);
            $ret = $this->auth->register($phone, $str, '', $phone, $extend);
        }
        
        $ret && $this->success(__('Logged in successful'), $this->auth->getUserinfo());
        $this->error($this->auth->getError());
    }
    
    
    /**
     * 获取openid与登录，不注册
     * 
     */
    public function wxopenid()
    {
        halt('暂未使用');
        $post = $this->request->post();
        (empty($post['code'])) && $this->error('参数有误');
        $session = $this->getSession($post['code']);

        $is_have = 0;  $user_info = [];

        $openid = $session['openid'];
        $have = db('user')->where('openid',$openid)->find();
        if(!empty($have)){
            $ret = $this->auth->login($openid);
            $user_info = $this->auth->getUserinfo();
            $is_have = 1;
            $ret && $this->success(__('Logged in successful'), compact('is_have','user_info'));
            $this->error($this->auth->getError());
        }
        $this->success('Get openid successful',compact('is_have','user_info'));
    }


    public function getUserInfo()
    {
        $info = $this->auth->getUserinfoSim();
        
        $this->success('Success',$info);
    }

    
    private function getSession($code)
    {
        $app_id = config('site.app_id');
        $app_secret = config('site.app_secret');
        // 微信登录 (获取session_key)
        $WxBase = new \app\api\service\WxBase($app_id, $app_secret);
        if (!$session = $WxBase->sessionKey($code)) {
            $this->error($WxBase->getError());
        }
        return $session;
    }


    public function editUser()
    {
        // halt('暂未使用');
        $params = I('post.');

        $update = [];
        if(empty($params['username'])){
            $this->error(__('请填写真实姓名'));
        }
        if (empty($params['idcard'])) {
            $this->error(__('请填写您的身份证号'));
        }
        $preg = '/^\d{6}(19|2\d)?\d{2}(0[1-9]|1[012])(0[1-9]|[12]\d|3[01])\d{3}(\d|X)?$/';
        if(!preg_match($preg,$params['idcard'])){
            $this->error(__('身份证号格式不正确'));
        }

        $update['username'] = $params['username'];
        $update['id_card_no'] = $params['idcard'];
        halt($update);
        $ret = db('user')->where('id',$this->auth->id)->update($update);
        $ret && $this->success('修改成功');
        $this->error('修改失败');
    }

    /**
     * 获取小程序码
     * 
     */
    public function getRQcode()
    {
        halt('暂未使用');
        $uid = $this->auth->id;
        $app_id = config('site.app_id');
        $app_secret = config('site.app_secret');
        $WxBase = new \app\api\service\WxBase($app_id, $app_secret);
        $access_token = $WxBase->getAccessToken();

        $param = [
            'path' => "pages/index/index?uid=$uid",
            'env_version' => 'release'  //trial 测试版，develop 开发版 ,release 正式版
        ];

        $url = "https://api.weixin.qq.com/wxa/getwxacode?access_token=$access_token";
        $ret = $WxBase->post($url,json_encode($param));
        
        $qrcodePath = ROOT_PATH . 'public/wxqrcode/';
        $filePath = ROOT_PATH . "public/wxqrcode/wxcode_$uid.jpg";

        // $ret = file_put_contents($filePath,$ret);

        if (!file_exists($filePath) && is_really_writable($qrcodePath)) {
            if (@$fp = fopen($filePath, 'w+' )) {
                fwrite ($fp, $ret);
                fclose ($fp);
            }
        }
        $this->success('Success',['url'=>cdnurl("/wxqrcode/wxcode_$uid.jpg",true)]);
    }

}
